var MenDianTable;
var DingDanTable2;
var WXTable2;
var map;
var marker;
/****列表信息*/
function showMenDianList() {
	showLoading("查询中...");
	$.ajax( {
		url : 'menDian/listPage.do',
		type : 'get',
		async:true,
		dataType : 'html',
		success : function(html) {
			$('#mainForm').html(html);
			queryMendianDatas();
			hideLoading();
			//绑定查询按钮 
		$('#searchMenDianBtn').click(function() {
			queryMendianList();
		});
	}
	});
}
function queryMendianDatas(){
		MenDianTable = $('#entTable').table( {
				width : '100%',
				form : {
					url : 'menDian/queryMendianPage.do',
					id : '#entSearchForm',
					type : 'post',
					pageNumberText : '#pageNum'
				},
				pageable : true,
				selectable : true,
				colums : [ {
					columnName : '名称',
					name : 'name',
					sortable:false,
					handle : "toAddMenDian"
				},{
					columnName : '地址',
					name : 'address',
					sortable:false
				}, {
					columnName : '联系人',
					name : 'lxr',
					sortable:false
				}, {
					columnName : '联系人电话',
					name : 'lxrTel',
					sortable:false
				},
				{
					columnName : '入驻时间',
					name:'crateDate',
				},
				{columnName:'属性',name:'weixiu',formatter:function(obj){
					var htm="";
					if(obj.chargeStation){htm+="充电"}
					if(obj.weixiu){if(""==htm){htm+="维修"}else{htm+="|维修"}}
					if(obj.xiaoshou){if(""==htm){htm+="销售"}else{htm+="|销售"}}
					if(obj.mobiCharge){if(""==htm){htm+="手机充电"}else{htm+="|手机充电"}}
		  			return htm;
		  			},
		  		sortable:false}
				]
			});
}
function queryMendianList(){
	showLoading("查询中...");
	queryMendianDatas();
	hideLoading();
}
function promptinfo()
{
    var s1 = document.getElementById('s1');
    var s2 = document.getElementById('s2');
    var s3 = document.getElementById('s3');
}
//去增加
function toAddMenDian(id) {
	var param = '?t=' + ts();
	var title="新增";
	if (id) {
		param += '&id=' + id;
		title="编辑";
	}
	$.get('menDian/toAddMenDian.do' + param, function(html) {
		$('#commonDialogDiv').html(html);
		$('#commonDialogDiv').dialog( {
			modal : true,
			title : title,
			width : 1124,
			height : 600,
			buttons : {
				'保存' : function() {
					saveAddMenDian();
				},
				'取消' : function() {
					$(this).dialog('close');
				}
			},
			beforeClose:function() {
				map=null;marker=null;
			     $("#map").remove();
			},
			close:function(){
				$(this).dialog('destroy');
			}
		});
		var _lat = $("#modelLatitude").val();
        var _lng =  $("#modelLongitude").val();
        if (_lat && _lng) {
		}else{
			_lat=39.90388637128857;
			_lng=116.40758371300763;
		}
 
//        //百度地图
//        var point = new BMap.Point(_lng, _lat); 
//		loadMap(point);
		//高德地图
		map = new AMap.Map("map",{center:new AMap.LngLat(_lng, _lat),level:17});	// 创建Map实例
		map.plugin(["AMap.ToolBar"],function(){
			toolBar = new AMap.ToolBar();
			map.addControl(toolBar);
		});
		loadMapbyLatLng(_lng,_lat);
		
		validator = $("#MenDianForm").validate( {
			rules : {
				"model.address" : {
					required : true,
					maxlength : 50
				},
				"model.name" : {
					required : true
				},
				"model.latitude" : {
					required : true
				},
				"model.longitude" : {
					required : true
				},
				"model.detailInfo" : {
					maxlength : 255
				}
			},
			messages : {
				"model.address" : {
					required : "必填"
				},
				"model.name" : {
					required : "必填"
				},
				"model.latitude" : {
					required : "必填"
				},
				"model.longitude" : {
					required : "必填"
				},
			}
		});
	});
}

//在百度地图上搜索
function initLoadMap() {
	var address = $("#searchAddr").val();
	var myGeo = new BMap.Geocoder();     
	// 将地址解析结果显示在地图上，并调整地图视野   
	myGeo.getPoint(address, function(point) {
		if (point) {
			map.centerAndZoom(point, 16);
			map.removeOverlay(marker);
			marker=new BMap.Marker(point);
			map.addOverlay(marker);
			$("#modelLatitude").val(point.lat);
        	$("#modelLongitude").val(point.lng);
        	getLocation(point);
		}else{
			alert("没有查询到");
		}
	}, address);
}
function loadMap(point) {
	map = new BMap.Map("map"); // 创建Map实例
	map.centerAndZoom(point, 15); // 初始化地图,设置中心点坐标和地图级别。
	map.enableScrollWheelZoom();    //启用滚轮放大缩小，默认禁用
    map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
	map.addControl(new BMap.ScaleControl());       // 添加比例尺控件
    map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
    map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件
	marker = new BMap.Marker(point);        // 创建标注     
    map.addOverlay(marker);   
	map.addEventListener("click", function(e){
		map.removeOverlay(marker); 
			$("#modelLatitude").val(e.point.lat);
        	$("#modelLongitude").val(e.point.lng);
        	getLocation(e.point);
        	point = new BMap.Point(e.point.lng, e.point.lat);
        	marker = new BMap.Marker(point);        // 创建标注     
        	map.addOverlay(marker);
	});
}

//地址编码用baidu，展示在高德
function initLoadBGoogleMap(){
	var address = $("#searchAddr").val();
	var myGeo = new BMap.Geocoder();     
	// 将地址解析结果显示在地图上，并调整地图视野   
	myGeo.getPoint(address, function(point) {
		if (point) {
			$("#modelLatitude").val(point.lat);
        	$("#modelLongitude").val(point.lng);
        	loadMapbyLatLng(point.lng,point.lat);
        	getLocationGoogle(point.lat,point.lng);
		}else{
			alert("没有查询到");
		}
	}, address);
}

//在谷歌类地图上地址反编码
function initLoadGoogleMap() {
	var address = $("#searchAddr").val();
	if(address!=null&&address!=''){
		var MGeocoder;
	    //加载地理编码插件
	    map.plugin(["AMap.Geocoder"], function() {        
	        MGeocoder = new AMap.Geocoder({ 
	            city:"010", //城市，默认：“全国”
	            radius:1000 //范围，默认：500
	        });
	        //返回地理编码结果 
	        AMap.event.addListener(MGeocoder, "complete", geocoder_CallBack); 
	        //地理编码
	        MGeocoder.getLocation(address); 
	    });
	}
}
//地理编码返回结果展示   
function geocoder_CallBack(data){
	var resultStr="";
    //地理编码结果数组
    var geocode = new Array();
    geocode = data.geocodes; 
    if(geocode.length>0){
    	    $("#modelLatitude").val(geocode[0].location.getLat());
        	$("#modelLongitude").val(geocode[0].location.getLng());
        	loadMapbyLatLng(geocode[0].location.getLng(),geocode[0].location.getLat());
    }
}

//载入高德地图
function loadMapbyLatLng(lng,lat){
		map.panTo(new AMap.LngLat(lng,lat));  
		if(marker){ marker.setMap(null);}
		marker=new AMap.Marker({				  
						icon:new AMap.Icon({    //复杂图标
								size:new AMap.Size(28,37),//图标大小
								image:"bettery/img/custom_a_j.png", //大图地址
								imageOffset:new AMap.Pixel(0,0)//相对于大图的取图位置
							}),
						position:new AMap.LngLat(lng,lat)
						});
		marker.setMap(map);  //在地图上添加点
	AMap.event.addListener(map,'click',function(e){  
		map.panTo(new AMap.LngLat(e.lnglat.getLng(),e.lnglat.getLat()));  
		$("#modelLatitude").val(e.lnglat.getLat());
        $("#modelLongitude").val(e.lnglat.getLng());
         marker.setPosition(new AMap.LngLat(e.lnglat.getLng(),e.lnglat.getLat()));         
	    getLocationGoogle(e.lnglat.getLat(),e.lnglat.getLng());
    });
}
	function getLocationGoogle(lat, lng) {
	if(lat&&lng){
		var lnglatXY= new AMap.LngLat(lng,lat);  
		//加载地理编码插件  
    map.plugin(["AMap.Geocoder"], function() {
        MGeocoder2 = new AMap.Geocoder({   
            radius: 1000,  
            extensions: "all"  
        });  
        //返回地理编码结果   
        AMap.event.addListener(MGeocoder2, "complete", geocoder_CallBack2);   
        //逆地理编码  
        MGeocoder2.getAddress(lnglatXY);   
    });  
		/*
		$.ajax( {
			url : "index/getLocationByGgLatlng.do?lat="+lat+"&lng="+lng+"&t=" + (new Date()),
			dataType : "json",
			type : 'get',
			async:false,
			success : function(data) {
				if(data.results.length>0){
					var first=data.results[0];
					var addr=first.formatted_address;
					addr=addr.replace('中国','');
					var i=addr.indexOf('邮政编码');
					var address_components=first.address_components;
					$("#m_province").val("");
					$("#m_city").val("");
					$("#m_town").val("");
					for(k=0;k<address_components.length;k++){
						var p1=address_components[k].types[0];
						var p2=address_components[k].types[1];
						if("administrative_area_level_1"==p1&&"political"==p2){
							$("#m_province").val(address_components[k].short_name);
						}else if("locality"==p1&&"political"==p2){
							$("#m_city").val(address_components[k].short_name);
						}else if("sublocality"==p1&&"political"==p2){
							$("#m_town").val(address_components[k].short_name);
						}
					}
					if(i>0){
						addr=addr.substring(0,i);
					}
					$("#searAddress").val(addr.trim());
				}else{
				}
			}
		});
		*/
		
		}
	}
	function geocoder_CallBack2(data){
		if(data.info=="OK"){
					var first=data.regeocode;
					var addr=first.formattedAddress;
					addr=addr.replace('中国','');
					var i=addr.indexOf('邮政编码');
					var address_components=first.addressComponent;
					$("#m_province").val("");
					$("#m_city").val("");
					$("#m_town").val("");
					
					$("#m_province").val(address_components.province);
					if(address_components.city.length==0){
						if((address_components.province).indexOf("北京")>=0||(address_components.province).indexOf("天津")>=0||(address_components.province).indexOf("上海")>=0||(address_components.province).indexOf("重庆")>=0){
							$("#m_city").val(address_components.province);
						}else if(null!=address_components.district&&address_components.district!=""){
                            $("#m_city").val(address_components.district);
                        }
					}else{
						$("#m_city").val(address_components.city);
					}
					if(null!=address_components.district&&address_components.district!=""){
						$("#m_town").val(address_components.district);
					}else if(null!=address_components.province&&""!=address_components.province){
						$("#m_town").val("市辖区");
					}
					if(i>0){
						addr=addr.substring(0,i);
					}
					
					
					$("#searAddress").val(addr.trim());
				}else{
					$("#m_province").val("");
					$("#m_city").val("");
					$("#m_town").val("");
				}
	}
function getLocation(pt) {
	var myGeo = new BMap.Geocoder();
	myGeo.getLocation(pt, function(data) {
		$('#searAddress').val(data.address);
	});
}

//去保存
function saveAddMenDian() {
	if (validator.form()) {
		$('#MenDianForm').ajaxSubmit( {
			url : 'menDian/saveMenDian.do',
			type : 'post',
			dataType : 'json',
			success : function(data) {
				if (data.success) {
					showDialog('保存成功');
					$('#commonDialogDiv').dialog('close');
					
					 queryMendianList();
				} else {
					showDialog('保存失败，' + data.message);
				}
			}
		});
	}
}
//批量删除 
function toDeleteMenDian() {
	var ids = '';
	$('.ids').each(function() {
		if (this.checked == true) {
			ids += 'ids=' + this.value + '&';
		}
	});
	if (ids.length == 0) {
		showDialog('请至少选择一条记录！');
		return;
	}
	$('#commonDialogDiv').html('<p>确定要删除记录信息？</p>');
	$('#commonDialogDiv').dialog( {
		modal : true,
		width : 250,
		height : 160,
		buttons : {
			'确定' : function() {
				$(this).dialog('close');
				$.ajax( {
					url : 'menDian/delete.do?' + ids,
					type : 'get',
					dataType : 'json',
					success : function(data) {
						if (data.success) {
							queryMendianList();
						} else {
							showDialog('删除失败，原因：' + data.message);
						}
					}
				});
			},
			'取消' : function() {
				$(this).dialog('close');
			}
		},close:function(){$(this).dialog('destroy');}
	});
}

//初始化下拉列表
function  initSsxSelect(){
	               $("#province").kendoDropDownList({
                        dataTextField: "name",
                        dataValueField: "name",
                        dataSource: {
    	                          serverFiltering: true,
		                          transport: {
		                                 read: { 
		                                        url: "district/queryRoots.do", 
                                                dataType: "json",
                                                type:'post'
                                         }}
                        }
                    });
                    var province = $("#city").kendoDropDownList({
                        autoBind: false,
                        cascadeFrom: "province",
                        optionLabel:  "请选择",
                        dataTextField: "name",
                        dataValueField: "name",
                        dataSource: {
    	                          serverFiltering: true,
		                          transport: {
		                                 read: { 
		                                        url: "district/queryByProvince.do", 
                                                dataType: "json",
                                                type:'post'
                                         }
                                  }
                        }
                    }).data("kendoDropDownList");

                    var city = $("#town").kendoDropDownList({
                        autoBind: false,
                        cascadeFrom: "city",
                        optionLabel:  "请选择",
                        dataTextField: "name",
                        dataValueField: "name",
                        dataSource: {
    	                          serverFiltering: true,
		                          transport: {
		                                 read: { 
		                                        url: "district/queryByParentId.do", 
                                                dataType: "json",
                                                type:'post'
                                         }}
                        }
                    }).data("kendoDropDownList");
}
//初始化下拉列表
function  initSsxSelect1(){
	               $("#province1").kendoDropDownList({
                        dataTextField: "name",
                        dataValueField: "name",
                        dataSource: {
    	                          serverFiltering: true,
		                          transport: {
		                                 read: { 
		                                        url: "district/queryRoots.do", 
                                                dataType: "json",
                                                type:'post'
                                         }}
                        }
                    });
                    var province = $("#city1").kendoDropDownList({
                        autoBind: false,
                        cascadeFrom: "province1",
                        optionLabel:  "请选择",
                        dataTextField: "name",
                        dataValueField: "name",
                        dataSource: {
    	                          serverFiltering: true,
		                          transport: {
		                                 read: { 
		                                        url: "district/queryByProvince.do", 
                                                dataType: "json",
                                                type:'post'
                                         }
                                  }
                        }
                    }).data("kendoDropDownList");

                    var city = $("#town1").kendoDropDownList({
                        autoBind: false,
                        cascadeFrom: "city1",
                        optionLabel:  "请选择",
                        dataTextField: "name",
                        dataValueField: "name",
                        dataSource: {
    	                          serverFiltering: true,
		                          transport: {
		                                 read: { 
		                                        url: "district/queryByParentId.do", 
                                                dataType: "json",
                                                type:'post'
                                         }}
                        }
                    }).data("kendoDropDownList");
}
//选择微信号
function  selectWeixin(){
	$('#kuDialogDiv').html('');
	$.get('menDian/weixinList.do?oldWxid='+$("#model_wxid").val()+'&t='+(new Date()), function(html) {
	$('#kuDialogDiv').dialog( {
						modal : true,
						title : '选择',
						width : 755,
						height : 460,
						buttons:{
							"返回":function(){
									$(this).dialog('close');
							}
						},
						open:function(event, ui){
							$('#kuDialogDiv').html(html);
							queryWeixinListPage('entSearchForm1');
						},
						close: function(event, ui) {
								$('#kuDialogDiv').remove();
								$("#parentDiv").html("<div id='kuDialogDiv' style='display: none'></div>");
						}
		});
});
}
function queryWeixinListPage(id){
	var url='weixinInfo/queryWeixinPage.do?t='+(new Date());
	$('#entTable2').table({
		width:'100%',
		form:{
				url:url,				
				id:"#"+id,
				type:'post',
				pageNumberText:"#pageNum"
		},
		pageable:true,							
		selectable:false,
		colums:[
				
				{columnName:'昵称',name:'nickname',sortable:false},
				{columnName:'微信openId',name:'id',sortable:false},
				{columnName:'头像',name:'sheadimgurl',sortable:false,formatter:function(obj){
		  			return "<img src=\""+obj.sheadimgurl+"\" />";
		  		}},
				{columnName:'操作',name:'', width:'90px',sortable:false,formatter:function(obj){
		  			if(obj.mendian){return "<a style='color:red; text-decoration:none;'>已是门店</a>"}
		  			else if(obj.status==2){return "<a style='color:red; text-decoration:none;'>取消关注</a>"}
		  			else{
		  				return "<input type='button' style='cursor: pointer' value='选择' onclick='checkWeixin(\""+obj.id+"\",\""+obj.nickname+"\")'>";
		  			}
		  			},
		  		sortable:false}
			   ]
		});
}
function checkWeixin(id,nick){
	$('#model_wxid').val(id);
	$('#model_nickname').val(nick);
	$('#kuDialogDiv').remove();
	$("#parentDiv").html("<div id='kuDialogDiv' style='display: none'></div>");
}
//管理员指定服务站页面
function zhiding(){
	$.get('menDian/zhiding.do?t='+(new Date()), function(html) {
	$('#kuDialogDiv').dialog( {
						modal : true,
						title : '指定',
						width : 755,
						height : 460,
						buttons:{
							"返回":function(){
									$(this).dialog('close');
							}
						},
						open:function(event, ui){
							$('#kuDialogDiv').html(html);
							queryZhidingFuwuZhan();
						},
						close: function(event, ui) {
								$('#kuDialogDiv').remove();
								$("#parentDiv").html("<div id='kuDialogDiv' style='display: none'></div>");
						}
		});
		
});
}

function queryZhidingFuwuZhan(){
	DingDanTable2 = $('#ZhiDingentTable').table({
		width:'100%',
		form:{
				url:'comm/search.do?t='+(new Date()),				
				id:'#zhidingFwzForm2',
				type:'post',
				pageNumberText:"#pageNum"
		},
		pageable:true,
		selectable:false,
		colums:[
				{columnName:'名称',width:'100px',name:'name',sortable:false},
				{columnName:'地址',name:'address',sortable:false},
				{columnName:'联系人', width:'90px',name:'lxr',sortable:false},
				{columnName:'联系电话',name:'lxrTel',sortable:false},
				{columnName:'操作',name:'', width:'80px',sortable:false,formatter:function(obj){
		  			return "<input type='button' style='cursor: pointer' value='指定' onclick='zhidingFuWuZhan("+obj.id+",\""+obj.name+"\")'>";
		  		},
		  		sortable:false}
			   ]
		});
}

//指定服务站
function zhidingFuWuZhan(id,name){
	$("#hideFuwuzhanId").val(id);
	$('#fuwuzhanName').val(name);
	$('#kuDialogDiv').remove();
	$("#parentDiv").html("<div id='kuDialogDiv' style='display: none'></div>");
}

//纯充电站隐藏微信
function processChargeClick(o){
	if('true'==$(o).val()){
		$("#model_wxid").val();
		$("#model_nickname").val();
		$("#weixinTr").hide();
		$("#model_detailInfo").css("height","99px");
	}else{
		$("#model_wxid").val($("#hideWxid").val());
		$("#model_nickname").val($("#hideNick").val());
		$("#weixinTr").show();
		$("#model_detailInfo").css("height","65px");
	}
}